#!/usr/bin/perl

# autolatex - xmi2eps_umbrello
# Copyright (C) 1998-07  Stephane Galland <galland@arakhne.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.

use strict;
use File::Basename;
use File::Spec;
use File::Copy;

my $extension = $ARGV[0];
my $from = $ARGV[1];
my $to = $ARGV[2];

my $targetDir = dirname($from);
my $wildcard = File::Spec->catfile("$targetDir","*.$extension");

my @existingFiles = ();

foreach my $file (glob("$wildcard")) {
	push @existingFiles, "$file";
}

my @CMD = ("umbrello",
	   "--export", "$extension",
	   "$from");

print join(' ',@CMD)."\n";
system(@CMD);

sub inarray(\@$) {
  foreach my $e (@{$_[0]}) {
    if (($e)&&($e eq $_[1])) {
      return $e;
    }
  }
  return undef;
}

my $resultingFile = undef;

foreach my $file (glob("$wildcard")) {
  if (!inarray(@existingFiles,"$file")) {
    $resultingFile = $file;
    last;
  }
}

if (($resultingFile)&&(-f "$resultingFile")) {
  if (-f "$to") {
    unlink("$to");
  }
  move("$resultingFile","$to");
  if (-f "$resultingFile") {
    unlink("$resultingFile");
  }
}
